package com.ruoyi.filler.controller;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.IpAddressUtils;
import com.ruoyi.consumer.domain.CFillingFacilit;
import com.ruoyi.consumer.domain.CFillingStation;
import com.ruoyi.consumer.service.impl.CFillingFacilitServiceImpl;
import com.ruoyi.consumer.service.impl.CFillingStationServiceImpl;
import com.ruoyi.consumer.utils.DistanceCalculator;
import com.ruoyi.consumer.utils.MapApiRequest;
import com.ruoyi.consumer.utils.QRCodeUtil;
import com.ruoyi.consumer.utils.pay.HttpStream;
import com.ruoyi.framework.websocket.WebSocketUsers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import static com.ruoyi.consumer.utils.PictureConverter.convertJsonArrayToString;
import static com.ruoyi.consumer.utils.PictureConverter.convertStringToJsonArray;

@Api(tags = "加注站")
@RestController
@RequestMapping("/api/fillingStation")
public class FillingStationController {

    @Autowired
    private CFillingStationServiceImpl fillingStationService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private CFillingFacilitServiceImpl fillingFacilitService;

    //上传加注站
    @ApiOperation("上传加注站")
    @GetMapping("/uploadFillingStation")
    public AjaxResult addFillingStation(@ApiParam(value = "上传者id", required = true) Integer fillerId,
                                        @ApiParam(value = "车辆id", required = false) Integer carId,
                                        @ApiParam(value = "加注站名字", required = true) String stationName,
                                        @ApiParam(value = "加注员名字", required = false) String stationUserName,
                                        @ApiParam(value = "加注站类型,0固定,1移动", required = true) Integer Status,
                                        @ApiParam(value = "加注站电话", required = true) String PhoneNumber,
                                        @ApiParam(value = "加注站图片", required = true) String stationImg,
                                        @ApiParam(value = "加注站经度", required = true) double lng,
                                        @ApiParam(value = "加注站纬度", required = true) double lat,
                                        @ApiParam(value = "加注站详细地址", required = true) String address) {
        Assert.notNull(fillerId, "上传者id不能为空");
        Assert.notNull(carId, "车辆id不能为空");
        Assert.notNull(Status, "加注站类型不能为空");
        Assert.notNull(address, "加注站详细地址不能为空");
        Assert.notNull(PhoneNumber, "加注站详细地址不能为空");
        Assert.notNull(lng, "加注站经度不能为空");
        Assert.notNull(lat, "加注站纬度不能为空");

        System.out.println("stationImg:" + stationImg);
        stationImg = convertJsonArrayToString(stationImg);
        System.out.println("strings:" + stationImg);

        StringBuilder sb = new StringBuilder();
        sb.append(lng);
        sb.append(",");
        sb.append(lat);

        // 调用腾讯地图API获取省市区
        Map<String, Object> addressMap = null;
        try {
            addressMap = (Map<String, Object>) MapApiRequest.getAddress(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        CFillingStation cFillingStation = new CFillingStation();
        cFillingStation.setFillerId(fillerId);
        List<CFillingStation> cFillingStations = fillingStationService.selectCFillingStationList(cFillingStation);
        System.out.println(cFillingStations);
        cFillingStation.setCarId(carId);
        cFillingStation.setStationProvince((String) addressMap.get("province"));
        cFillingStation.setStationCity((String) addressMap.get("city"));
        cFillingStation.setStationArea((String) addressMap.get("district"));
        cFillingStation.setStationLatitude(lat);
        cFillingStation.setStationLongitude(lng);
        cFillingStation.setStationState(Status);
        cFillingStation.setStationName(stationName);
        cFillingStation.setStationUsername(stationUserName);
        cFillingStation.setStationPlace(address);
        cFillingStation.setStationImg(stationImg);
        cFillingStation.setStationPhone(PhoneNumber);
        if (cFillingStations.size() > 0) {
            CFillingStation fillingStation = cFillingStations.get(0);
            fillingStation.setCarId(carId);
            fillingStation.setStationProvince((String) addressMap.get("province"));
            fillingStation.setStationCity((String) addressMap.get("city"));
            fillingStation.setStationArea((String) addressMap.get("district"));
            fillingStation.setStationLatitude(lat);
            fillingStation.setStationLongitude(lng);
            fillingStation.setStationState(Status);
            fillingStation.setStationName(stationName);
            fillingStation.setStationUsername(stationUserName);
            fillingStation.setStationPlace(address);
            fillingStation.setStationImg(stationImg);
            fillingStation.setStationPhone(PhoneNumber);
            return AjaxResult.success("FillingStation", fillingStationService.updateCFillingStation(fillingStation));
        }
        return AjaxResult.success("FillingStation", fillingStationService.insertCFillingStation(cFillingStation));
    }

    //根据fillerId查询加注站
    @ApiOperation("根据fillerId查询加注站")
    @GetMapping("/selectFillingStation")
    public AjaxResult selectFillingStation(@ApiParam(value = "上传者id", required = true) Integer fillerId) {
        CFillingStation cFillingStation = new CFillingStation();
        cFillingStation.setFillerId(fillerId);
        List<CFillingStation> cFillingStations = fillingStationService.selectCFillingStationList(cFillingStation);
        if (cFillingStations.isEmpty()) {
            return AjaxResult.success("没有找到加注站");
        }
        CFillingStation fillingStation = cFillingStations.get(0);
        if (fillingStation.getStationImg() == null) {
            return AjaxResult.success("data", fillingStation);
        }
        String string = convertStringToJsonArray(fillingStation.getStationImg());
        fillingStation.setStationImg(string);
        return AjaxResult.success("data", fillingStation);
    }


    @ApiOperation("获取加注站列表")
    @GetMapping("/getFillingStationList")
    public AjaxResult getFillingStationList(@ApiParam(value = "Station省", required = true) String StationProvince,
                                            @ApiParam(value = "Station市", required = true) String StationCity,
                                            @ApiParam(value = "Station区", required = true) String StationArea,
                                            @ApiParam(value = "当前页码,从1开始", required = true) Integer pageNum,
                                            @ApiParam(value = "每页显示记录数", required = true) Integer pageSize,
                                            @ApiParam(value = "我的纬度", required = true) double fixedLat,
                                            @ApiParam(value = "我的经度", required = true) double fixedLng) {
        Assert.notNull(StationProvince, "省不能为空");
        Assert.notNull(StationCity, "市不能为空");
        Assert.notNull(StationArea, "区不能为空");
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("create_time desc");


        if (StationProvince.equals("") || StationCity.equals("") || StationArea.equals("")) {
            CFillingStation cFillingStation = new CFillingStation();
            List<CFillingStation> FillingStationList = fillingStationService.selectCFillingStationList(cFillingStation);
            //计算距离
            calculateDistance(fixedLat, fixedLng, FillingStationList);
            //            将距离拼接到返回结果中
            List<AjaxResult> ajaxResultList = packageResult(FillingStationList);
            return AjaxResult.success("FillingStation", ajaxResultList);
        }


        List<CFillingStation> filteredStations = filterStationsByLocation(StationProvince, StationCity, StationArea);
        if (filteredStations == null) {
            return AjaxResult.error("没有找到加注站");
        }
        //计算距离
        calculateDistance(fixedLat, fixedLng, filteredStations);
        //            将距离拼接到返回结果中
        List<AjaxResult> ajaxResultList = packageResult(filteredStations);

        if (fixedLat == 0 || fixedLng == 0) {
            return AjaxResult.success("FillingStation", ajaxResultList);
        }
        Map<Double, Integer> distanceMap = new HashMap<>();


        // 计算每个加注站与我的位置的距离
        for (CFillingStation station : filteredStations) {
            double distance = DistanceCalculator.calculateDistance(fixedLat, fixedLng, station.getStationLatitude(), station.getStationLongitude());
            distanceMap.put(distance, station.getStationId());
        }
        // 按距离排序
        List<Double> distanceList = new ArrayList<>(distanceMap.keySet());
        distanceList.sort(Double::compareTo);
        List<CFillingStation> FillingStation = new ArrayList<>();
        for (Double distance : distanceList) {
            FillingStation.add(fillingStationService.selectCFillingStationByStationId(distanceMap.get(distance)));
        }
        //计算距离
        calculateDistance(fixedLat, fixedLng, FillingStation);
        //            将距离拼接到返回结果中
        List<AjaxResult> ajaxResults = packageResult(FillingStation);
        return AjaxResult.success("FillingStation", ajaxResults);
    }

    private List<CFillingStation> filterStationsByLocation(String province, String city, String area) {
        CFillingStation cFillingStation = new CFillingStation();
        List<CFillingStation> FillingStationList = fillingStationService.selectCFillingStationList(cFillingStation);
        if (FillingStationList.size() == 0) {
            return null;
        }
        List<CFillingStation> filteredStations = new ArrayList<>();
        //按省市区过滤
        for (CFillingStation station : FillingStationList) {
            String string = convertStringToJsonArray(station.getStationImg());
            station.setStationImg(string);
            if (station.getStationProvince().equals(province) &&
                    station.getStationCity().equals(city) &&
                    station.getStationArea().equals(area)) {
                filteredStations.add(station);
            }
        }
        //按省市过滤
        if (filteredStations.size() == 0) {
            for (CFillingStation station : FillingStationList) {
                if (station.getStationProvince().equals(province) &&
                        station.getStationCity().equals(city)) {
                    filteredStations.add(station);
                }
            }
        }
        //按省过滤
        if (filteredStations.size() == 0) {
            for (CFillingStation station : FillingStationList) {
                if (station.getStationProvince().equals(province)) {
                    filteredStations.add(station);
                }
            }
        }
        //如果没有找到加注站，展示所有加注站
//        if (filteredStations.size() == 0) {
//            filteredStations = FillingStationList;
//        }

        return filteredStations;
    }

    //根据加注站id查询加注站
    @ApiOperation("根据加注站id查询加注站")
    @GetMapping("/selectFillingStationByStationId")
    public AjaxResult selectFillingStationByStationId(@ApiParam(value = "加注站id", required = true) Integer stationId) throws Exception {
        Assert.notNull(stationId, "加注站id不能为空");
        CFillingStation cFillingStation = fillingStationService.selectCFillingStationByStationId(stationId);
        if (cFillingStation == null) {
            return AjaxResult.error("没有找到加注站");
        }
        String lng_lat = cFillingStation.getStationLongitude() + "," + cFillingStation.getStationLatitude();
        String url = MapApiRequest.getMapImg(lng_lat);
        String string = convertStringToJsonArray(cFillingStation.getStationImg());
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("stationImg", string);
        ajaxResult.put("mapImg", url);
        ajaxResult.put("stationName", cFillingStation.getStationName());
        ajaxResult.put("stationPhone", cFillingStation.getStationPhone());
        ajaxResult.put("stationUsername", cFillingStation.getStationUsername());
        //经纬度
        ajaxResult.put("stationLongitude", cFillingStation.getStationLongitude());
        ajaxResult.put("stationLatitude", cFillingStation.getStationLatitude());
        //地址详情
        ajaxResult.put("stationPlace", cFillingStation.getStationPlace());
        //离我的距离
        ajaxResult.put("distance", DistanceCalculator.calculateDistance(30.274150, 120.155150, cFillingStation.getStationLatitude(), cFillingStation.getStationLongitude()));
        return AjaxResult.success("data", ajaxResult);
    }

    /**
     * 根据经纬度返回省市区
     *
     * @param lng
     * @param lat
     * @return
     * @throws Exception
     */
    @ApiOperation("根据经纬度返回省市区")
    @GetMapping("/getAddress")
    public AjaxResult getAddress(@ApiParam(value = "经度", required = true) double lng,
                                 @ApiParam(value = "纬度", required = true) double lat) throws Exception {
        Assert.notNull(lng, "经度不能为空");
        Assert.notNull(lat, "纬度不能为空");
        StringBuilder sb = new StringBuilder();
        sb.append(lng);
        sb.append(",");
        sb.append(lat);
        Map<String, Object> addressMap = (Map<String, Object>) MapApiRequest.getAddress(sb.toString());
        return AjaxResult.success("data", addressMap);
    }

    //计算距离方法
    private void calculateDistance(double lat1, double lng1, List<CFillingStation> cFillingStation) {
        for (CFillingStation station : cFillingStation) {
            double distance = DistanceCalculator.calculateDistance(lat1, lng1, station.getStationLatitude(), station.getStationLongitude());
            redisCache.setCacheObject("distance:" + station.getStationId(), distance);
        }
    }

    //包装返回结果方法
    public List<AjaxResult> packageResult(List<CFillingStation> cFillingStation) {
        List<AjaxResult> ajaxResultList = new ArrayList<>();
        for (CFillingStation station : cFillingStation) {
            if (station.getStationState() == 1) {
                continue;
            }
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("distance", (Double) redisCache.getCacheObject("distance:" + station.getStationId()));
            ajaxResult.put("station", station);
            ajaxResultList.add(ajaxResult);
        }
        return ajaxResultList;
    }

    /**
     * 流动加注站
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation("流动加注站")
    @GetMapping("/mobileFillingStation")
    public AjaxResult mobileFillingStation(@ApiParam(value = "当前页码,从1开始", required = true) Integer pageNum,
                                           @ApiParam(value = "每页显示记录数", required = true) Integer pageSize
//                                           @ApiParam(value = "我的纬度", required = true) double fixedLat,
//                                           @ApiParam(value = "我的经度", required = true) double fixedLng
    ) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("create_time desc");
        CFillingStation cFillingStation = new CFillingStation();
        cFillingStation.setStationState(1);
        List<CFillingStation> FillingStationList = fillingStationService.selectCFillingStationList(cFillingStation);
        WebSocketUsers.sendMessageToUsersByText("获取流动加注车");
        return AjaxResult.success("FillingStation", FillingStationList);

    }

    //实时更新流动加注车位置
    @ApiOperation("实时更新流动加注车位置")
    @GetMapping("/updateMobileFillingStation")
    public AjaxResult updateMobileFillingStation(@ApiParam(value = "加注站id", required = true) Integer stationId,
                                                 @ApiParam(value = "加注站经度", required = true) double lng,
                                                 @ApiParam(value = "加注站纬度", required = true) double lat) {
        Assert.notNull(stationId, "加注站id不能为空");
        Assert.notNull(lng, "加注站经度不能为空");
        Assert.notNull(lat, "加注站纬度不能为空");
        CFillingStation cFillingStation = fillingStationService.selectCFillingStationByStationId(stationId);
        cFillingStation.setFlowLat(lat);
        cFillingStation.setFlowLon(lng);
        fillingStationService.updateCFillingStation(cFillingStation);

        return AjaxResult.success("FillingStation", cFillingStation);

    }

    //更改加注站模式
    @ApiOperation("更改加注站模式")
    @GetMapping("/updateStationState")
    public AjaxResult updateStationState(@ApiParam(value = "加注站id", required = true) Integer stationId) {
        Assert.notNull(stationId, "加注站id不能为空");
        CFillingStation cFillingStation = fillingStationService.selectCFillingStationByStationId(stationId);
        if (cFillingStation == null) {
            return AjaxResult.error("没有找到加注站");
        }
        if (cFillingStation.getStationState() == 0) {
            cFillingStation.setStationState(1);
        } else if (cFillingStation.getStationState() == 1) {
            cFillingStation.setStationState(0);
        }
        fillingStationService.updateCFillingStation(cFillingStation);
        CFillingStation Station = fillingStationService.selectCFillingStationByStationId(stationId);
        return AjaxResult.success("FillingStation", Station.getStationState());
    }


    //生成加注机专用二维码
    @ApiOperation("生成加注机专用二维码")
    @GetMapping("/createStationQrCode")
    public AjaxResult createStationQrCode(@ApiParam(value = "加注站id", required = true) String sn,
                                          @ApiParam(value = "加注站名", required = true) String name,
                                          HttpServletResponse response) {
        CFillingFacilit cFillingFacilit = new CFillingFacilit();
        cFillingFacilit.setFacilitSn(sn);
        List<CFillingFacilit> cFillingFacilits1 = fillingFacilitService.selectCFillingFacilitList(cFillingFacilit);
        if (!cFillingFacilits1.isEmpty()) {
            return AjaxResult.success("该加注机已存在", cFillingFacilits1.get(0).getFacilitImg());
        }
        cFillingFacilit.setFacilitName(name);
        int i = fillingFacilitService.insertCFillingFacilit(cFillingFacilit);
        if (i > 0) {
            CFillingFacilit cFillingFacilitNoFacImg = new CFillingFacilit();
            cFillingFacilitNoFacImg.setFacilitId(cFillingFacilit.getFacilitId());
            cFillingFacilitNoFacImg.setFacilitSn(sn);

            String Path = "/home/ruoyi/uploadPath/upload/sn/" + sn + ".png";
//            String Path = "D:/ruoyi/uploadPath/upload/sn/" + sn + ".png";
            try {

                String url = "https://zsky.lytx.net.cn/api/qrsn/";
                String path = cFillingFacilitNoFacImg.getFacilitId().toString();
                String fileName = url + path;
                System.out.println("fileName:" + fileName);

                // 构建一个HttpServletResponseWrapper，以便在QRCodeUtil.encode内部构建响应流
                HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);

                // 创建 ByteArrayOutputStream 以获取生成的 BufferedImage
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                // 在QRCodeUtil.encode方法内部构建响应流，并获取生成的 BufferedImage
                BufferedImage image = QRCodeUtil.encode(fileName, responseWrapper);

          /*      // 这里可以使用 byteArrayOutputStream 中的数据进行其他操作
                byte[] data = byteArrayOutputStream.toByteArray();*/

                // 将 BufferedImage 写入到文件流
                try (FileOutputStream outStream = new FileOutputStream(new File(Path))) {
                    ImageIO.write(image, "png", outStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            String path = IpAddressUtils.getAddressInfo() + "/profile/upload/sn/" + sn + ".png";
            cFillingFacilitNoFacImg.setFacilitImg(path);
            cFillingFacilitNoFacImg.setStatus(3);
            fillingFacilitService.updateCFillingFacilit(cFillingFacilitNoFacImg);


            return AjaxResult.success("msg", path);

        } else {
            return AjaxResult.error("添加失败");
        }
    }
}



